import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { fetchFeedsPage } from "../../api";

export const fetchFeedsPageAction = createAsyncThunk(
  'feeds/fetch',
  async (page=1) => {
    const data = await fetchFeedsPage(page)
    return data
  }
)

export const feedsSlice = createSlice({
  name: 'feeds',
  initialState: {
    loading: false,
    byId: {},
    pagination: {},
    page: 1,
    count: 0,
  },
  reducers: {
    changePage(state, {payload: page}) {
      state.page = page
    }
  },
  extraReducers: {
    [fetchFeedsPageAction.pending](state) {
      state.loading = true
    },
    [fetchFeedsPageAction.fulfilled](state,
      {payload:
         {page, count, feeds:{entities: {feeds}, result}}
      })
    {
      state.loading = false
      // state.byId = {...state.byId, ...feeds}
      Object.assign(state.byId, feeds)
      state.count = count
      state.page = page
      state.pagination[page] = result
    }
  }
})

export const feedsPageSelector = (feedsState, current) => {
  const page = current || feedsState.page
  return (feedsState.pagination[page] || [])
    .map(id => feedsState.byId[id])
}

export const feedsSelector = (state) => {
  return state.feeds
}

export const feedsReduer = feedsSlice.reducer